package client_commands;

import client.ClientApplication;
import client.ClientBindObject;
import client_tree.User;

public class SERV_UNREGCommand extends Command {

	
	public SERV_UNREGCommand(String parameter) {
		setCode(SERV_UNREG);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ClientApplication theApp) {

		String username = getParameter();
		
		int status = OFFLINE_STATUS;

		User user = theApp.getClientModel().getOnlineModel().getUserByUsername(username);
		
		// null je ako se user deregistrovao, a da je njegov status bio invisible
		if (user == null) {
			user = theApp.getClientModel().getOfflineModel().getUserByUsername(username);
		}
		
		if (user == null) {
			theApp.getClientUser().removeFromBlockList(username);
			return true;
		}
		
		user.setStatus(status);
		
		theApp.getClientModel().addUser(user);
		
		if ( ClientApplication.clientBinding.get(username) != null ) {
			
			ClientBindObject cbo = ClientApplication.clientBinding.get(username);
			if (cbo.getDialog() != null) {
				cbo.getDialog().setConnection(null);
				cbo.getDialog().setSendButtonRights(false);
			}
			
			cbo.getConnection().writeData( Long.toString(cbo.getConnection().getConnectionID()) );
			
			try {
				Thread.sleep(1000);
			}
			catch (InterruptedException ie) {
				ie.printStackTrace();
			}
			
			cbo.getConnection().quitConnection();
			cbo.setConnection(null);
		}
		
		return true;
	}
	
}
